<template>
  <div>
    <el-popover
      style="overflow-y: auto; "
      placement="bottom"
      trigger="click">

      <el-input
        style="margin-bottom: 10px"
        v-model="搜索内容"
        clearable>
        <el-button slot="append" icon="el-icon-search" @click="search" size="small" >搜索</el-button>
      </el-input>


<!--      树结构-->
      <el-tree
        style="width:auto"
        ref="tree"
        :props="props"
        :load="loadNode"
        lazy
        :check-strictly="false"
        @check-change="handleCheckChange"
        show-checkbox
        node-key="id"
        :default-expanded-keys="[]"
        :default-checked-keys="[]"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span v-if="需要高亮节点数组.indexOf(data.id) !== -1" style="background-color: yellow">{{ node.label }}</span>
          <span v-else>{{ node.label }}</span>

        </span>

      </el-tree>
<!--      输入框 用来显示选中的节点内容-->
      <el-input slot="reference"
                style="width:380px"
                v-model="value.name"
                placeholder="节点"
                clearable
                readonly
                @clear="handleIptClear">
      </el-input>
    </el-popover>
  </div>
</template>
<script>
export default {
  data() {
    return {
      props: {
        label: 'name',
        children: 'zones'
      },
      count: 1,
      value:{id:'', name: ''},
      需要高亮节点数组:['1-0', '0-4', '0-1'],
      搜索内容:''
    };
  },
  methods: {

    // 清空输入框内容
    handleIptClear(){
      console.log('清空输入框内容')
      this.$refs.tree.setCheckedNodes([])
      this.value.id = ''
      this.value.name = ''
    },
    /**
     * 更新被选中的值
     */
    updateCheck(){
      const seltedNodes = this.$refs.tree.getCheckedNodes()
      console.log(seltedNodes)
      const ids = seltedNodes.map(n => n.id)
      const names = seltedNodes.map(n => n.name)
      this.value.id = ids + ''
      this.value.name = names + ''
    },
    // checkbox被选中或取消选中
    handleCheckChange(arg1, arg2, arg3){
      console.log(arg1, arg2, arg3);
      this.updateCheck()
    },
    // 节点被点击
    handleNodeClick(arg1, arg2, arg3){
      console.log('nodes:', arg1, arg2, arg3)
      this.updateCheck()
    },

    模拟数据(node){
      let 级别 = node.level
      let arr = []
      for (let i = 0; i < 5; i++) {
        let id = 级别 + '-' + i
        let name = '第' + 级别 + '级-' + i
        arr.push({ name: name, id:id })
      }
      return arr;
    },

    /**
     * 懒加载节点数据
     * 这里调用API获取数据 目前都是模拟的数据
     * @param node
     * @param resolve
     * @returns {*}
     */
    loadNode(node, resolve) {

      let that = this
      //这里模拟数据 调用接口
      setTimeout(() => {
        let data = that.模拟数据(node)
        resolve(data);
        this.updateCheck()
      }, 500);
    }
  }
};
</script>
